package com.ccf.business.etl.flow.mq;

import com.ccf.business.etl.model.FlowLog;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 描述：
 * 延迟日志信息
 * @author xianggj
 * @Date 2021/12/27 18:30
 **/
public class DelayedLogInfo  implements Delayed {


    /**
     *  触发时间
     */
    private long time;

    private FlowLog flowLog;

    /**
     * 延时时间
     * 每0.5秒取一次数据
     */
    private static final long DELAY_TIME = 5000;

    public DelayedLogInfo(FlowLog flowLog) {
        this.flowLog = flowLog;
        this.time = System.currentTimeMillis() + DELAY_TIME;
    }

    /**
     * 返回这个对象剩余的延时时间
     * 固定延迟0.5秒
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return time - System.currentTimeMillis();
    }

    /**
     * 控制队列中元素优先级
     * @param o
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        DelayedLogInfo item = (DelayedLogInfo) o;
        long diff = this.time - item.time;
        //表示第一个元素到期 所有元素都取出来
        if (diff >= 0) {
            return -1;
        }else {
            return 1;
        }
    }


    public static void main(String[] args) throws InterruptedException {
        DelayedLogInfo item1 = new DelayedLogInfo(new FlowLog());
        DelayedLogInfo item2 = new DelayedLogInfo(new FlowLog());
        DelayedLogInfo item3 = new DelayedLogInfo(new FlowLog());
        DelayQueue<DelayedLogInfo> queue = new DelayQueue<>();
        queue.put(item1);
        queue.put(item2);
        queue.put(item3);
        System.out.println("begin time:" + LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        DelayedLogInfo take = queue.take();
        DelayedLogInfo[] delayedLogInfos = queue.toArray(new DelayedLogInfo[0]);
        queue.clear();
        for (DelayedLogInfo takes : delayedLogInfos){
            System.out.format("name:{%s}, time:{%s}\n",takes.flowLog.getFlowName(), LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));

        }

    }
}
